package com.aiyun.websocket.tiowebsocketdemo.config;


import java.io.IOException;

import javax.annotation.PostConstruct;

import com.aiyun.websocket.tiowebsocketdemo.core.annotation.EnableTioWebsocket;
import org.tio.core.Tio;
import org.tio.server.ServerTioConfig;
import org.tio.websocket.server.WsServerStarter;
import org.tio.websocket.server.handler.IWsMsgHandler;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnBean(annotation = EnableTioWebsocket.class)
public class TioConfiguration {

	private final TioProperties tioProperties;

	private final IWsMsgHandler iWsMsgHandler;

	private WsServerStarter wsServerStarter = null;

	public TioConfiguration(TioProperties tioProperties, IWsMsgHandler iWsMsgHandler) {
		this.tioProperties = tioProperties;
		this.iWsMsgHandler = iWsMsgHandler;
	}

	@Bean
	public WsServerStarter wsServerStarter() throws IOException {
		this.wsServerStarter = new WsServerStarter(tioProperties.getServer().getPort(), iWsMsgHandler);
		return this.wsServerStarter;
	}


	@Bean
	public ServerTioConfig serverTioConfig(WsServerStarter wsServerStarter) throws IOException {
		ServerTioConfig serverTioConfig = wsServerStarter.getServerTioConfig();
		serverTioConfig.setName(tioProperties.getServer().getProtocalName());
		//设置心跳超时时间
		serverTioConfig.setHeartbeatTimeout(tioProperties.getServer().getHeartbeatTimeout());
		wsServerStarter.start();
		return serverTioConfig;
	}

}
